#include <SPI.h>
#include <Ethernet.h>

//The MAC address should be printed on a sticker on your Ethernet shield
byte mac[] = {0x90, 0xA2, 0xDA, 0x0E, 0x04, 0x31};
/* The IP address will change based on where you are set up.
Find your IP Address with Examples->Ethernet->DhcpAddressPrinter */
//IPAddress ip(69, 133, 100, 191); //arduino
IPAddress ip(10, 33, 50, 199); //at Miami
EthernetServer server(80);  // create a server at port 80

String HTTP_req;          // stores the HTTP request
boolean LED_status = 0;   // state of LED, off by default
const int voltageSize = 500;
float highest = 0;
int voltage[voltageSize];
float peakVoltage = 0;
float loadVoltage = 0;
float shuntResist = 46.8;
float loadResist = 0;
float root2 = 1.414213562;
float rmsVoltage = 0;
float truePower = 0;

void setup()
{
    Ethernet.begin(mac, ip);  // initialize Ethernet device
    server.begin();           // start to listen for clients
    Serial.begin(9600);       // for diagnostics
    pinMode(7, OUTPUT);       // Solid state driver
    pinMode(8, OUTPUT);       // LED driver
}

void loop()
{
    EthernetClient client = server.available();  // try to get client

    if (client) {  // got client?
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {   // client data available to read
                char c = client.read(); // read 1 byte (character) from client
                HTTP_req += c;  // save the HTTP request 1 char at a time
                // last line of client request is blank and ends with \n
                // respond to client only after last line received
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    client.println("Content-Type: text/html");
                    client.println("Connection: close");
                    client.println();
                    // send web page
                    client.println("<!DOCTYPE html>");
                    client.println("<html>");
                    client.println("<head>");
                    client.println("    <title>JETS Power Integration</title>");
                    client.println("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
                    //client.println("    <meta http-equiv=\"refresh\" content=\"5\">");
                    client.println("    <link rel=\"stylesheet\" href=\"http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css\" />");
                    client.println("    <script src=\"http://code.jquery.com/jquery-1.9.1.min.js\"></script>");
                    client.println("    <script src=\"http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js\"></script>");
                    client.println("    <script src=\"http://code.jquery.com/ui/1.10.2/jquery-ui.js\"></script>");
  		    client.println("	<script type=\"text/javascript\">");
  		    client.println("		function changeText(){");
  		    client.println("			if (document.getElementById('status').innerHTML == \"Uncheck to turn switch OFF\") {");
  		    client.println("				document.getElementById('status').innerHTML = \"Check to turn switch ON\";");
      		    client.println("			}");
      		    client.println("			else {");
      		    client.println("				document.getElementById('status').innerHTML = \"Uncheck to turn switch OFF\";");
      		    client.println("			}");
      		    client.println("		}");
      		    client.println("	</script>");
                    client.println("</head>");
                    client.println("<body>");
                    client.println("<div data-role=\"page\">");
                    client.println("    <div data-role=\"header\" data-theme=\"c\">");
                    client.println("        <center><img src=\"http://trgorczynski.com/images/JetsLogo80.png\"></center>");
                    client.println("    </div>");
                    client.println("    <div data-role=\"content\">");
                    client.println("        <div class=\"ui-grid-a\">");
                    client.println("            <div class=\"ui-block-a\"><div class=\"ui-bar ui-bar-e\" style=\"height:30px\"><center><h3>OUTLET STATUS<h3></center></div></div>");
                    client.println("            <div class=\"ui-block-b\"><div class=\"ui-bar ui-bar-e\" style=\"height:30px\"><center><h3>POWER CONSUMPTION<h3></center></div></div>");
                    client.println("            <div class=\"ui-block-a\"><div class=\"ui-bar ui-bar-e\" style=\"height:60px\">");
                    client.println("            <center><p id=\"status\">Checked is on.</p></center>");
                    client.println("            <form style=\"margin: 0 auto; width:40px;\" method=\"get\">");
                    ProcessCheckbox(client);
                    client.println("            </form>");
                    client.println("            </div></div>");
                    delay(1500);
                    getPower();
                    delay(500);
                    client.println("            <div class=\"ui-block-b\"><div class=\"ui-bar ui-bar-e\" style=\"height:60px\"><center><u>");
                    client.println(truePower, 5);
                    client.println("            </u> WATTS</center></div></div>");
                    client.println("        </div>");
                    client.println("    </div>");
                    client.println("    <div data-role=\"footer\">");
                    client.println("        <p><center><font size=\"2\">Copyright &copy; JETS Power Integration Inc.</font></center></p>");
                    client.println("    </div>");
                    client.println("</div>");
                    client.println("</body>");
                    client.println("</html>");

                    Serial.print(HTTP_req);
                    HTTP_req = "";    // finished with request, empty string
                    break;
                }
                // every line of text received from the client ends with \r\n
                if (c == '\n') {
                    // last character on line of received text
                    // starting new line with next character read
                    currentLineIsBlank = true;
                } 
                else if (c != '\r') {
                    // a text character was received from client
                    currentLineIsBlank = false;
                }
            } // end if (client.available())
        } // end while (client.connected())
        delay(1);      // give the web browser time to receive the data
        client.stop(); // close the connection
    } // end if (client)
}

void getPower() {  
  //Sample the voltage to find the highest value
  for (int i = 0; i < voltageSize; i++) {
    voltage[i] = analogRead(A3);
    Serial.println(voltage[i]);
    
    if (voltage[i] >= highest)
      highest = voltage[i];
  }
  
  Serial.print("Highest: ");
  Serial.println(highest);
  
  peakVoltage = highest/1023*5;
  loadVoltage = 5-peakVoltage; 
  Serial.print("Peak Voltage: ");
  Serial.println(loadVoltage, 8);
  
  loadResist = (loadVoltage/peakVoltage)*shuntResist;
  
  rmsVoltage = loadVoltage / root2;
  Serial.print("RMS Voltage: ");
  Serial.println(rmsVoltage, 8);
  
  truePower = pow(rmsVoltage, 2) / loadResist;
  Serial.print("True Power (watts): ");
  Serial.println(truePower, 8);
  
  highest = 0;
}

// switch LED and send back HTML for LED checkbox
void ProcessCheckbox(EthernetClient cl)
{
    if (HTTP_req.indexOf("LED2=2") > -1) {  // see if checkbox was clicked
        // the checkbox was clicked, toggle the LED
        if (LED_status) {
            LED_status = 0;
        }
        else {
            LED_status = 1;
        }
    }
    
    if (LED_status) {    // switch LED on
        digitalWrite(7, LOW);
        digitalWrite(8, HIGH);
        // checkbox is checked
        cl.println("<input type=\"checkbox\" name=\"LED2\" value=\"2\" onclick=\"submit();\" checked>");
    }
    else {              // switch LED off
        digitalWrite(7, HIGH);
        digitalWrite(8, LOW);
        // checkbox is unchecked
        cl.println("<input type=\"checkbox\" name=\"LED2\" value=\"2\" onclick=\"submit();\">");
    } 
}